package cn.com.config;

import cn.com.mapper.UserDataSourceConfigMapper;
import cn.com.model.UserDataSourceConfig;
import com.sun.istack.internal.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Objects;

@Component
public class UserDataSourceManager {

    @Resource(name = "user")
    private UserRoutingDataSource userRoutingDataSource;

    @Autowired
    private UserDataSourceConfigMapper userDataSourceConfigMapper;

    public void registerUserDataSource(@NotNull Long userId) {
        UserDataSourceContext.setUserId(userId);
        DataSource dataSource = (DataSource) userRoutingDataSource.lookUpUserDataSource(userId);
        if(dataSource == null) {
            UserDataSourceConfig userDataSource = userDataSourceConfigMapper.selectByUserId(userId);
            if(Objects.nonNull(userDataSource)) {
                userRoutingDataSource.registerUserDataSource(userId, DataSourceBuilder.create()
                        .username(userDataSource.getUsername())
                        .url(userDataSource.getUrl())
                        .password(userDataSource.getPassword())
                        .driverClassName(userDataSource.getDriver())
                        .build());
            } else {
                throw new RuntimeException("该用户不存在数据源配置");
            }
        }
    }
}
